package com.hengtiansoft.lfy.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hengtiansoft.lfy.LFYApplication;
import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.base.BaseActivity;
import com.hengtiansoft.lfy.chart.DemoHXSDKHelper;
import com.hengtiansoft.lfy.chart.action.UpdateUserSexJson;
import com.hengtiansoft.lfy.chart.action.UpdateUserSignatureJson;
import com.hengtiansoft.lfy.chart.bean.BaseResult;
import com.hengtiansoft.lfy.chart.net.JsonListRequest;
import com.hengtiansoft.lfy.chart.net.VolleyUtil;
import com.hengtiansoft.lfy.chart.utils.UserUtils;
import com.hengtiansoft.lfy.constants.Constants;
import com.hengtiansoft.lfy.entity.ServiceResult;
import com.hengtiansoft.lfy.entity.UploadAvatarEntity;
import com.hengtiansoft.lfy.entity.UserInfo;
import com.hengtiansoft.lfy.net.NetHelper;
import com.hengtiansoft.lfy.net.NetUtils;
import com.hengtiansoft.lfy.utils.CommonUtils;
import com.hengtiansoft.lfy.utils.Config;
import com.hengtiansoft.lfy.chart.applib.utils.HXPreferenceUtils;
import com.hengtiansoft.lfy.widget.CodeDialog;
import com.hengtiansoft.lfy.widget.MyPopupWindow;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.squareup.picasso.Picasso;
import com.umeng.socialize.media.Constant;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 我的详情页面
 */
public class MyInformationActivity extends BaseActivity
        implements OnClickListener {
   private static String TAG = "MyInformationActivity";
    private RelativeLayout mRlAvatar;
    private RelativeLayout mRlNickname;
    private RelativeLayout mRlPassword;
    private RelativeLayout mRlCode;
    private RelativeLayout mRlSex;
    private RelativeLayout mRlLogout;
    private RelativeLayout mRlMobile;
    private RelativeLayout mRlSignature;
    private ImageView mIvAvatar;
    private TextView mTvNickname;
    private TextView mTvMobile;
    private LinearLayout ll;
    private TextView mTvSignature;
    private MyPopupWindow popWindow;
    private LayoutInflater layoutInflater;
    private TextView photograph, albums;
    private LinearLayout cancel;
    private TextView mTvSex;
  public static final int PHOTOZOOM = 0; // 相册
    public static final int PHOTOTAKE = 1; // 拍照
    public static final int IMAGE_COMPLETE = 2; // 截取结果
    public static final int CROPREQCODE = 3; // 截取
    // 加载等待
    private ProgressDialog pd;
    Context mContext;
      private String message1 ;
    private boolean hasSendJson = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_my_information);
        message1=getString(R.string.update_fail);
        initView();
        setListener();
        refresh();
    }

    private void initView() {
        pd = new ProgressDialog(mContext);
        pd.setCanceledOnTouchOutside(false);
        pd.setMessage(getString(R.string.modifying));
        layoutInflater = (LayoutInflater) getSystemService(
                Context.LAYOUT_INFLATER_SERVICE);
        mRlAvatar = (RelativeLayout) findViewById(R.id.rl_avatar);
        mRlSignature = (RelativeLayout) findViewById(R.id.rl_Signature);
        mRlNickname = (RelativeLayout) findViewById(R.id.rl_nickname);
        mRlPassword = (RelativeLayout) findViewById(R.id.rl_password);
        mTvSignature = (TextView) findViewById(R.id.tv_Signature);
        mRlCode = (RelativeLayout) findViewById(R.id.rl_code);
        mRlSex = (RelativeLayout) findViewById(R.id.rl_sex);
        mTvSex = (TextView) findViewById(R.id.tv_sex);
        if (null != HXPreferenceUtils.getInstance().getCurrentUserSex()) {
            if (HXPreferenceUtils.getInstance().getCurrentUserSex()
                    .equals("m")) {
                mTvSex.setText(getString(R.string.man));
            } else if (HXPreferenceUtils.getInstance().getCurrentUserSex()
                    .equals("f")) {
                mTvSex.setText(getString(R.string.woman));
            }
        }
        if (HXPreferenceUtils.getInstance().getCurrentUserThreeLogin()!=0) {
            mRlPassword.setVisibility(View.GONE);
        }
        mRlLogout = (RelativeLayout) findViewById(R.id.rl_logout);
        mRlMobile = (RelativeLayout) findViewById(R.id.rl_mobile);
        mIvAvatar = (ImageView) findViewById(R.id.iv_avatar);
        mTvNickname = (TextView) findViewById(R.id.tv_nickname);
        mTvMobile = (TextView) findViewById(R.id.tv_mobile);
        File destDir = new File(Environment.getExternalStorageDirectory()
                + Constants.IMAGE_CACHE_PATH);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
    }

    private void setListener() {
        mRlAvatar.setOnClickListener(this);
        mRlNickname.setOnClickListener(this);
        mRlPassword.setOnClickListener(this);
        mRlLogout.setOnClickListener(this);
        mRlMobile.setOnClickListener(this);
        mRlCode.setOnClickListener(this);
        mRlSex.setOnClickListener(this);
        mRlSignature.setOnClickListener(this);
    }


    /**
     * 刷新界面上的数据
     */
    public void refresh() {
        // 性别，m：男，f：女
        setCurrentUserAvatar(HXPreferenceUtils.getInstance().getCurrentUserAvatar(),mContext, mIvAvatar);
        setUserNick(
                HXPreferenceUtils.getInstance().getCurrentUserNick(),
                mTvNickname);
        if (null != HXPreferenceUtils.getInstance().getCurrentUserMobile()) {
            mTvMobile.setText(
                    HXPreferenceUtils.getInstance().getCurrentUserMobile());
        }
        if (null != HXPreferenceUtils.getInstance().getCurrentUserSignature()) {
            mTvSignature.setText(
                    HXPreferenceUtils.getInstance().getCurrentUserSignature());
        }
    }
    /**
     * 设置当前用户头像
     */
    public static void setCurrentUserAvatar(String url,Context context,
                                            ImageView imageView) {
        if (!TextUtils.isEmpty(url)) {
            if(url.indexOf("http")==-1) {
                Picasso.with(context)
                        .load(Constants.GETIMAGE + url)
                        .placeholder(R.drawable.img_head).into(imageView);
            }else{
                Picasso.with(context)
                        .load(url)
                        .placeholder(R.drawable.img_head).into(imageView);
            }
        } else {
            Picasso.with(context).load(R.drawable.img_head)
                    .into(imageView);
        }
    }
    /**
     * 设置用户昵称
     */
    public static void setUserNick(String username, TextView textView) {
        if (!TextUtils.isEmpty(username) ) {
            textView.setText(username);
        } else {
            textView.setText("");
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.rl_avatar:
            showPopupWindow(mRlAvatar);
            break;
        case R.id.rl_nickname:
            LayoutInflater factory = LayoutInflater.from(mContext);// 提示框
            final View dialogview = factory.inflate(R.layout.dialog_feedback,
                    null);// 这里必须是final的
            final EditText edit = (EditText) dialogview
                    .findViewById(R.id.tv_dialog_new_userpwd);// 获得输入框对象
            edit.setFilters(
                    new InputFilter[] { new InputFilter.LengthFilter(10) }); // 其中10最大输入字数
            if (HXPreferenceUtils.getInstance().getCurrentUserNick() != null) {
                edit.setText(
                        HXPreferenceUtils.getInstance().getCurrentUserNick());
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle(getString(R.string.change_nickname)).setView(dialogview).setNegativeButton(getString(R.string.cancel),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            closeDialog(dialog, true);
                        }
                    });
            builder.setPositiveButton(getString(R.string.ok),
                    new DialogInterface.OnClickListener() {

                        public void onClick(final DialogInterface dialog,
                                int which) {
                            if (edit.getText().toString().equals("")) {
                                Toast.makeText(mContext, getString(R.string.user_cannot_null),
                                        Toast.LENGTH_SHORT).show();
                                closeDialog(dialog, false);
                            } else {
                                pd.show();
                                UpdateUserNicknameJsonRequest(edit.getText().toString());

                                closeDialog(dialog, true);
                            }
                        }
                    });
            builder.show();
            break;
            case R.id.rl_Signature:
                LayoutInflater factory1 = LayoutInflater.from(mContext);// 提示框
                final View dialogview1 = factory1.inflate(R.layout.dialog_feedback,
                        null);// 这里必须是final的
                final EditText edit1 = (EditText) dialogview1
                        .findViewById(R.id.tv_dialog_new_userpwd);// 获得输入框对象
                edit1.setFilters(
                        new InputFilter[] { new InputFilter.LengthFilter(20) }); // 其中20最大输入字数
                if (HXPreferenceUtils.getInstance()
                        .getCurrentUserSignature() != null) {
                    edit1.setText(HXPreferenceUtils.getInstance()
                            .getCurrentUserSignature());
                }

                AlertDialog.Builder builder1 = new AlertDialog.Builder(mContext);
                builder1.setTitle(getString(R.string.change_signature)).setView(dialogview1)
                        .setNegativeButton(getString(R.string.cancel), null);
                builder1.setPositiveButton(getString(R.string.ok),
                        new DialogInterface.OnClickListener() {

                            public void onClick(final DialogInterface dialog,
                                                int which) {
                                pd.show();
                                UpdateUserSignatureJson updateUserSignatureJson = new UpdateUserSignatureJson(
                                        Config.getUserToken(),
                                        edit1.getText().toString(),
                                        Config.getUserName());
                                UpdateUserSignatureJsonRequest(
                                        Constants.UpdateUserSignature,
                                        updateUserSignatureJson,
                                        edit1.getText().toString());
                            }
                        });
                builder1.show();
                break;

            case R.id.rl_password:
            LayoutInflater factory3 = LayoutInflater.from(mContext);// 提示框
            final View dialogview3 = factory3.inflate(R.layout.dialog_password,
                    null);// 这里必须是final的
            final EditText oldpassword = (EditText) dialogview3
                    .findViewById(R.id.tv_dialog_old_userpwd);// 获得输入框对象
            final EditText newpassword = (EditText) dialogview3
                    .findViewById(R.id.tv_dialog_new_userpwd);// 获得输入框对象
            final EditText renewpassword = (EditText) dialogview3
                    .findViewById(R.id.tv_dialog_new_reuserpwd);// 获得输入框对象
            AlertDialog.Builder builder3 = new AlertDialog.Builder(mContext);
            builder3.setTitle(getString(R.string.change_passwd)).setView(dialogview3).setNegativeButton(
                    getString(R.string.cancel), new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            closeDialog(dialog, true);
                        }
                    });
            builder3.setPositiveButton(getString(R.string.ok),
                    new DialogInterface.OnClickListener() {

                        public void onClick(final DialogInterface dialog,
                                int which) {
                            if (oldpassword.getText().toString().equals("")
                                    | oldpassword.getText().toString()
                                            .equals(null)) {
                                Toast.makeText(mContext, getString(R.string.input_old_password),
                                        Toast.LENGTH_LONG).show();
                                closeDialog(dialog, false);
                            } else if (newpassword.getText().toString()
                                    .equals("")
                                    | newpassword.getText().toString()
                                            .equals(null)) {
                                Toast.makeText(mContext, getString(R.string.input_new_password),
                                        Toast.LENGTH_LONG).show();
                                closeDialog(dialog, false);
                            } else if (!renewpassword.getText().toString()
                                    .equals(newpassword.getText().toString())) {
                                Toast.makeText(mContext,getString(R.string.input_password_other),
                                        Toast.LENGTH_LONG).show();
                                closeDialog(dialog, false);
                            } else if (newpassword.getText().toString().trim()
                                    .length() < 6) {
                                Toast.makeText(mContext, getString(R.string.passwd_less6),
                                        Toast.LENGTH_LONG).show();
                                closeDialog(dialog, false);
                            } else {
                                pd.show();
                                String oldpasswordMd5=CommonUtils.MD5(oldpassword.getText().toString());
                                String newpasswordMd5=CommonUtils.MD5(newpassword.getText().toString());
                                UpdateUserPasswordRequest(
                                        oldpasswordMd5,
                                        newpasswordMd5);
                                closeDialog(dialog, true);
                            }

                        }
                    });
            builder3.show();
            break;
            case R.id.rl_code:
                // 二维码
                final CodeDialog codeDialog = new CodeDialog(mContext,
                        Config.getUserName(),
                        HXPreferenceUtils.getInstance().getCurrentUserNick(),
                        HXPreferenceUtils.getInstance().getCurrentUserSex());
                codeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                codeDialog.show();
                break;
        case R.id.rl_mobile:
            LayoutInflater mobilefactory = LayoutInflater.from(mContext);// 提示框
            final View mobiledialogview = mobilefactory
                    .inflate(R.layout.dialog_mobile, null);// 这里必须是final的
            final EditText mobileedit = (EditText) mobiledialogview
                    .findViewById(R.id.edt_dialog_mobile);// 获得输入框对象
            mobileedit.setFilters(
                    new InputFilter[] { new InputFilter.LengthFilter(11) });
            if (!TextUtils.isEmpty(HXPreferenceUtils.getInstance().getCurrentUserMobile())) {
                mobileedit.setText(
                        HXPreferenceUtils.getInstance().getCurrentUserMobile());
            }
            AlertDialog.Builder mobilebuilder = new AlertDialog.Builder(
                    mContext);
            mobilebuilder.setTitle(getString(R.string.change_phone)).setView(mobiledialogview)
                    .setNegativeButton(getString(R.string.cancel),
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    closeDialog(dialog, true);
                                }
                            });
            mobilebuilder.setPositiveButton(getString(R.string.ok),
                    new DialogInterface.OnClickListener() {

                        public void onClick(final DialogInterface dialog,
                                int which) {
                            // pd.show();
                            Log.i(TAG, mobileedit.getText().toString());
                           /* if (mobileedit.getText().toString().trim() == null
                                    | mobileedit.getText().toString().trim()
                                            .equals("")) {
                                pd.show();
                                if (!hasSendJson) {
                                    updateMobile(null);
                                }
                                closeDialog(dialog, true);
                            } else*/ if (!CommonUtils.isMobileNum(
                                    mobileedit.getText().toString().trim())) {

                                Toast.makeText(mContext, getString(R.string.phone_Invalid),
                                        Toast.LENGTH_SHORT).show();
                                // 进行以下设置将不能关闭dialog
                                closeDialog(dialog, false);
                            } else if (mobileedit.getText().toString().trim()
                                    .equals(HXPreferenceUtils.getInstance().getCurrentUserMobile())) {
                                Toast.makeText(mContext,
                                        getString(R.string.phone_other),
                                        Toast.LENGTH_SHORT).show();
                                closeDialog(dialog, false);
                            } else {
                                pd.show();
                                if (!hasSendJson) {
                                    updateMobile(
                                            mobileedit.getText().toString()
                                                    .trim());
                                }
                                closeDialog(dialog, true);
                            }
                        }
                    });
            mobilebuilder.show();
            break;
            case R.id.rl_sex:
                LayoutInflater factory2 = LayoutInflater.from(mContext);// 提示框
                final View dialogview2 = factory2.inflate(R.layout.dialog_sex,
                        null);// 这里必须是final的
                final RelativeLayout mRlBoy = (RelativeLayout) dialogview2
                        .findViewById(R.id.rl_boy);
                final RelativeLayout mRlGirl = (RelativeLayout) dialogview2
                        .findViewById(R.id.rl_girl);
                final ImageView mIvBoyUnchoose = (ImageView) dialogview2
                        .findViewById(R.id.iv_boy_unchoose);
                final ImageView mIvBoyChoose = (ImageView) dialogview2
                        .findViewById(R.id.iv_boy_choose);
                final ImageView mIvGirlUnchoose = (ImageView) dialogview2
                        .findViewById(R.id.iv_girl_unchoose);
                final ImageView mIvGirlChoose = (ImageView) dialogview2
                        .findViewById(R.id.iv_girl_choose);
                if (null != HXPreferenceUtils.getInstance().getCurrentUserSex()) {
                    if (HXPreferenceUtils.getInstance().getCurrentUserSex()
                            .equals("m")) {
                        mIvBoyUnchoose.setVisibility(View.GONE);
                        mIvBoyChoose.setVisibility(View.VISIBLE);
                        mIvGirlUnchoose.setVisibility(View.VISIBLE);
                        mIvGirlChoose.setVisibility(View.GONE);
                    } else if (HXPreferenceUtils.getInstance().getCurrentUserSex()
                            .equals("f")) {
                        mIvBoyUnchoose.setVisibility(View.VISIBLE);
                        mIvBoyChoose.setVisibility(View.GONE);
                        mIvGirlUnchoose.setVisibility(View.GONE);
                        mIvGirlChoose.setVisibility(View.VISIBLE);
                    }
                }
                AlertDialog.Builder builder2 = new AlertDialog.Builder(mContext);
                builder2.setTitle(getString(R.string.my_information_sex)).setView(dialogview2);
                final AlertDialog dialog = builder2.show();
                mRlBoy.setOnTouchListener(new OnTouchListener() {

                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        mIvBoyUnchoose.setVisibility(View.GONE);
                        mIvBoyChoose.setVisibility(View.VISIBLE);
                        mIvGirlUnchoose.setVisibility(View.VISIBLE);
                        mIvGirlChoose.setVisibility(View.GONE);
                        UpdateUserSexJson updateUserSexJson = new UpdateUserSexJson(
                                Config.getUserToken(), "m",
                                Config.getUserName());
                        UpdateUserSexJsonRequest(Constants.UpdateUserSex,
                                updateUserSexJson, "m");
                        dialog.dismiss();
                        return false;
                    }
                });
                mRlGirl.setOnTouchListener(new OnTouchListener() {

                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        mIvBoyUnchoose.setVisibility(View.VISIBLE);
                        mIvBoyChoose.setVisibility(View.GONE);
                        mIvGirlUnchoose.setVisibility(View.GONE);
                        mIvGirlChoose.setVisibility(View.VISIBLE);
                        UpdateUserSexJson updateUserSexJson = new UpdateUserSexJson(
                                Config.getUserToken(), "f",
                                Config.getUserName());
                        UpdateUserSexJsonRequest(Constants.UpdateUserSex,
                                updateUserSexJson, "f");
                        dialog.dismiss();
                        return false;
                    }
                });
                break;
        case R.id.rl_logout:
            new AlertDialog.Builder(this).setTitle(getString(R.string.prompt)).setMessage(getString(R.string.loginout_title))
                    .setPositiveButton(getString(R.string.ok),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    logout();
                                }
                            })
                    .setNegativeButton(getString(R.string.cancel), null).show();
            break;
        default:
            break;
        }
    }
    private void UpdateUserSignatureJsonRequest(
            String UpdateUserSignatureJsonUrl,
            UpdateUserSignatureJson mUploadAvatarJson, final String Signature) {
        Log.i(TAG,
                "<uploadAvatarRequest>--<onResponse>--上传的JSon数据：  GetTokenJson = "
                        + mUploadAvatarJson);

        Type type = new TypeToken<BaseResult>() {
        }.getType();
        JsonListRequest<BaseResult> request = new JsonListRequest<BaseResult>(
                this, Request.Method.POST, UpdateUserSignatureJsonUrl,
                mUploadAvatarJson.toString(), null, null, type, false,
                new Response.Listener<BaseResult>() {
                    @Override
                    public void onResponse(BaseResult arg0) {
                        Log.i(TAG,
                                "<uploadAvatarRequest>--<onResponse>--服务器返回的JSon数据：  arg0 = "
                                        + arg0);
                        int code = 1;
                        String message = null;
                        message = arg0.getMessage();
                        code = arg0.getCode();
                        Log.i(TAG,
                                "<uploadAvatarRequest>--<onResponse>--服务器返回的JSon数据：  message = "
                                        + message);
                        Log.i(TAG,
                                "<uploadAvatarRequest>--<onResponse>--服务器返回的JSon数据：  code = "
                                        + code);
                        if (code == 0) {
                            HXPreferenceUtils.getInstance()
                                    .setCurrentUserSignature(Signature);
                            mTvSignature.setText(Signature);
                            Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                                    .show();
                        } else {
                            Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                                    .show();
                        }
                        pd.dismiss();
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
                NetworkResponse response = arg0.networkResponse;
                if (response != null) {
                    try {
                        String json = new String(response.data,
                                HttpHeaderParser.parseCharset(
                                        response.headers));
                        Log.i(TAG,
                                "<uploadAvatarRequest>--<onErrorResponse> -- json = "
                                        + json);
                        Log.i(TAG,
                                "<uploadAvatarRequest>--<onErrorResponse> -- response.data = "
                                        + response.data);
                        Log.i(TAG,
                                "<uploadAvatarRequest>--<onErrorResponse> -- response.headers = "
                                        + response.headers);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                if (arg0 != null && arg0.toString().contains(
                        "com.android.volley.NoConnectionError")) {
                    Toast.makeText(mContext,
                            getString(R.string.network_unavailable),
                            Toast.LENGTH_SHORT).show();
                } else if (arg0 != null && arg0.toString()
                        .contains("com.android.volley.ServerError")) {
                    Toast.makeText(mContext,
                            getString(
                                    R.string.service_temporarily_unavailable),
                            Toast.LENGTH_SHORT).show();
                } else if (arg0 != null && arg0.toString()
                        .contains("com.android.volley.TimeoutError")) {
                    Toast.makeText(mContext,
                            getString(R.string.time_out_error),
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(mContext,
                            getString(R.string.request_fail),
                            Toast.LENGTH_SHORT).show();
                }
                Log.i(TAG,
                        "<uploadAvatarRequest>--<onErrorResponse>--服务器请求失败： arg0 = "
                                + arg0);
                Log.i(TAG,
                        "<uploadAvatarRequest>--<onErrorResponse>--服务器请求失败： response = "
                                + response);
                pd.dismiss();
            }

        });
        VolleyUtil.addRequest(request);
    }
    private void UpdateUserSexJsonRequest(String UpdateUserSexJsonUrl,
                                          UpdateUserSexJson mUploadAvatarJson, final String sex) {
        Log.i(TAG,
                "<uploadAvatarRequest>--<onResponse>--上传的JSon数据：  GetTokenJson = "
                        + mUploadAvatarJson);

        Type type = new TypeToken<BaseResult>() {
        }.getType();
        JsonListRequest<BaseResult> request = new JsonListRequest<BaseResult>(
                this, Request.Method.POST, UpdateUserSexJsonUrl,
                mUploadAvatarJson.toString(), null, null, type, false,
                new Response.Listener<BaseResult>() {
                    @Override
                    public void onResponse(BaseResult arg0) {
                        Log.i(TAG,
                                "<uploadAvatarRequest>--<onResponse>--服务器返回的JSon数据：  arg0 = "
                                        + arg0);
                        int code = 1;
                        String message = null;
                        message = arg0.getMessage();
                        code = arg0.getCode();
                        Log.i(TAG,
                                "<uploadAvatarRequest>--<onResponse>--服务器返回的JSon数据：  message = "
                                        + message);
                        Log.i(TAG,
                                "<uploadAvatarRequest>--<onResponse>--服务器返回的JSon数据：  code = "
                                        + code);
                        if (code == 0) {
                            HXPreferenceUtils.getInstance()
                                    .setCurrentUserSex(sex);
                            if (sex.equals("m")) {
                                mTvSex.setText("男");
                            } else if (sex.equals("f")) {
                                mTvSex.setText("女");
                            }

                            Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                                    .show();
                        } else {
                            Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                                    .show();
                        }
                        pd.dismiss();
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
                NetworkResponse response = arg0.networkResponse;
                if (response != null) {
                    try {
                        String json = new String(response.data,
                                HttpHeaderParser.parseCharset(
                                        response.headers));
                        Log.i(TAG,
                                "<uploadAvatarRequest>--<onErrorResponse> -- json = "
                                        + json);
                        Log.i(TAG,
                                "<uploadAvatarRequest>--<onErrorResponse> -- response.data = "
                                        + response.data);
                        Log.i(TAG,
                                "<uploadAvatarRequest>--<onErrorResponse> -- response.headers = "
                                        + response.headers);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                if (arg0 != null && arg0.toString().contains(
                        "com.android.volley.NoConnectionError")) {
                    Toast.makeText(mContext,
                            getString(R.string.network_unavailable),
                            Toast.LENGTH_SHORT).show();
                } else if (arg0 != null && arg0.toString()
                        .contains("com.android.volley.ServerError")) {
//                    Toast.makeText(mContext,
//                            getString(
//                                    R.string.service_temporarily_unavailable),
//                            Toast.LENGTH_SHORT).show();
                } else if (arg0 != null && arg0.toString()
                        .contains("com.android.volley.TimeoutError")) {
                    Toast.makeText(mContext,
                            getString(R.string.time_out_error),
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(mContext,
                            getString(R.string.request_fail),
                            Toast.LENGTH_SHORT).show();
                }
                Log.i(TAG,
                        "<uploadAvatarRequest>--<onErrorResponse>--服务器请求失败： arg0 = "
                                + arg0);
                Log.i(TAG,
                        "<uploadAvatarRequest>--<onErrorResponse>--服务器请求失败： response = "
                                + response);
                pd.dismiss();
            }

        });
        VolleyUtil.addRequest(request);
    }
    /**
     * 退出登录
     */
    void logout() {
        final ProgressDialog pd = new ProgressDialog(mContext,
                ProgressDialog.THEME_HOLO_LIGHT);
        String st = getResources().getString(R.string.Are_logged_out);
        pd.setMessage(st);
        pd.setCanceledOnTouchOutside(false);
        pd.show();
        DemoHXSDKHelper.getInstance().logout(true, new EMCallBack() {

            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    public void run() {
                        Config.setUserToken(null);
                        Config.setUserName(null);
                        HXPreferenceUtils.getInstance().removeCurrentUserInfo();
                        pd.dismiss();
                        startActivity(
                                new Intent(mContext, LoginActivityV2.class));
                        // 重新显示登陆页面
                        finish();

                    }
                });
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        pd.dismiss();
                        Toast.makeText(mContext, getString(R.string.loginout_fail), Toast.LENGTH_SHORT)
                                .show();
                    }
                });
            }
        });

    }

    @SuppressWarnings("deprecation")
    private void showPopupWindow(View parent) {
        if (popWindow == null) {
            View view = layoutInflater.inflate(R.layout.pop_select_photo, null);
            popWindow = new MyPopupWindow(view, LayoutParams.MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT, new MyPopupWindow.OnDismiss() {
                        @Override
                        public void onDismiss() {
                            // 调节背景的亮度
                            CommonUtils.backgroundAlpha(
                                    MyInformationActivity.this, 1.0f);
                        }
                    });
            initPop(view);
        }
        // 调节背景的亮度
      //  CommonUtils.backgroundAlpha(MyInformationActivity.this, 0.6f);
        popWindow.setAnimationStyle(android.R.style.Animation_InputMethod);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        popWindow.setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
    }

    public void initPop(View view) {
        photograph = (TextView) view.findViewById(R.id.photograph);// 拍照
        albums = (TextView) view.findViewById(R.id.albums);// 相册
        cancel = (LinearLayout) view.findViewById(R.id.cancel);// 取消
        photograph.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {

                /**
                 * 下面这句还是老样子，调用快速拍照功能，至于为什么叫快速拍照，大家可以参考如下官方
                 * 文档，you_sdk_path/docs/guide/topics/media/camera.html
                 * 我刚看的时候因为太长就认真看，其实是错的，这个里面有用的太多了，所以大家不要认为
                 * 官方文档太长了就不看了，其实是错的，这个地方小马也错了，必须改正
                 */
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                // 下面这句指定调用相机拍照后的照片存储的路径
                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(new File(
                                Environment.getExternalStorageDirectory()
                                        + Constants.IMAGE_CACHE_PATH,
                                "avatar.jpg")));
                Log.i(TAG, Environment.getExternalStorageDirectory()
                        + Constants.IMAGE_CACHE_PATH);
                startActivityForResult(intent, PHOTOTAKE);
            }
        });
        albums.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                popWindow.dismiss();
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                /**
                 * 下面这句话，与其它方式写是一样的效果，如果：
                 * intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                 * intent.setType(""image/*");设置数据类型 如果朋友们要限制上传到服务器的图片类型时可以直接写如：
                 * "image/jpeg 、 image/png等的类型"
                 * 这个地方小马有个疑问，希望高手解答下：就是这个数据URI与类型为什么要分两种形式来写呀？有什么区别？
                 */
                intent.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        "image/*");
                startActivityForResult(intent, PHOTOZOOM);
            }
        });
        cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                popWindow.dismiss();
            }
        });
    }

    /**
     * 图片选择及拍照结果
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
        case PHOTOZOOM:// 相册
            startPhotoZoom(data.getData());
            break;
        case PHOTOTAKE:// 拍照
            File temp = new File(Environment.getExternalStorageDirectory()
                    + Constants.IMAGE_CACHE_PATH + "/avatar.jpg");
            startPhotoZoom(Uri.fromFile(temp));
            break;
        case IMAGE_COMPLETE:
            if (popWindow != null) {
                popWindow.dismiss();
            }
            pd.show();
            /**
             * 非空判断大家一定要验证，如果不验证的话， 在剪裁之后如果发现不满意，要重新裁剪，丢弃
             * 当前功能时，会报NullException，小马只 在这个地方加下，大家可以根据不同情况在合适的 地方做判断处理类似情况
             *
             */
            if (data != null) {
                setPicToView(data);
            }

            break;
        default:
            break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
                Bitmap photo = extras.getParcelable("data");
                Drawable drawable = new BitmapDrawable(photo);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                photo.compress(Bitmap.CompressFormat.JPEG, 60, stream);
                byte[] bytes = stream.toByteArray();
                // 将图片流以字符串形式存储下来
                final String picStr = android.util.Base64.encodeToString(bytes,
                        android.util.Base64.DEFAULT);
                Log.d(TAG,
                        "上传图片压缩大小：" + stream.toByteArray().length / 1024 + "k");
                // 上传为头像
                uploadAvatarRequest(picStr,drawable);

        }
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        /*
         * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
         * yourself_sdk_path/docs/reference/android/content/Intent.html
         * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能, 是直接调本地库的，
         */
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(uri, "image/*");
            // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
            intent.putExtra("crop", "true");
            // aspectX aspectY 是宽高的比例
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            // outputX outputY 是裁剪图片宽高
            intent.putExtra("outputX", 150);
            intent.putExtra("outputY", 150);
            intent.putExtra("return-data", true);
            startActivityForResult(intent, IMAGE_COMPLETE);

    }

    /**
     * @param url
     *            图片地址
     * @return
     */
    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String setObject(Object obj_model) {
        Gson gson = new Gson();
        return gson.toJson(obj_model);
    }



    /**
     * 上传头像
     *
     * @param picStr
     * @param drawable
     */
    private void uploadAvatarRequest(String picStr, final Drawable drawable) {
        NetHelper.UploadImage(self, picStr, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                int code = 1;
                String message = null;
                UploadAvatarEntity uploadAvatarEntity= (UploadAvatarEntity) rspData;
                String data = (String) uploadAvatarEntity.getData();
                message = rspData.getMessage();
                code = rspData.getRetcode();
                Log.i(TAG,
                        "<uploadAvatarRequest>--<onResponse>--服务器返回的JSon数据：  message = "
                                + message);
                Log.i(TAG,
                        "<uploadAvatarRequest>--<onResponse>--服务器返回的JSon数据：  code = "
                                + code);
                if (code == 0) {
                    HXPreferenceUtils.getInstance()
                            .setCurrentUserAvatar(
                                    Constants.GETIMAGE + data);
                    UserUtils.setCurrentUserAvatar(
                            MyInformationActivity.this, mIvAvatar);
                    Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                            .show();
                } else {
                    Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                            .show();
                }
                pd.dismiss();
            }

            @Override
            public void failed(String msg) {
                Toast.makeText(mContext,
                        msg,
                        Toast.LENGTH_SHORT).show();
                pd.dismiss();
            }
        },UploadAvatarEntity.class);
    }

    private void UpdateUserPasswordRequest(String oldPasswordMD5,
            String newPasswordMD5) {
        NetHelper.UpdateUserPassword(self, oldPasswordMD5, newPasswordMD5, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                int code = 1;
                String message = null;
                message = rspData.getMessage();
                code = rspData.getRetcode();
                Log.i(TAG,
                        "<uploadAvatarRequest>--<onResponse>--服务器返回的JSon数据：  message = "
                                + message);
                Log.i(TAG,
                        "<uploadAvatarRequest>--<onResponse>--服务器返回的JSon数据：  code = "
                                + code);
                if (code == 0) {
                    Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                            .show();
                } else {
                    Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                            .show();
                }
                pd.dismiss();
            }

            @Override
            public void failed(String msg) {
                Toast.makeText(mContext, msg, Toast.LENGTH_LONG)
                        .show();
                pd.dismiss();
            }
        }, ServiceResult.class);

    }





    private void UpdateUserNicknameJsonRequest( final String nickname) {
        NetHelper.UpdateUserNickname(self,nickname,new NetUtils.NetCallBack<ServiceResult>(){

            @Override
            public void success(ServiceResult rspData) {
                int code = 1;
                String message = null;
                message = rspData.getMessage();
                code = rspData.getRetcode();
                Log.i(TAG,
                        "<uploadAvatarRequest>--<onResponse>--服务器返回的JSon数据：  message = "
                                + message);
                Log.i(TAG,
                        "<uploadAvatarRequest>--<onResponse>--服务器返回的JSon数据：  code = "
                                + code);
                if (code == 0) {
                    HXPreferenceUtils.getInstance()
                            .setCurrentUserNick(nickname);
                    mTvNickname.setText(nickname);
                    // 更新当前用户的nickname 此方法的作用是在ios离线推送时能够显示用户nick
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            EMClient.getInstance().pushManager()
                                    .updatePushNickname(
                                            HXPreferenceUtils
                                                    .getInstance()
                                                    .getCurrentUserNick());
                        }
                    }).start();
                    Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                            .show();
                } else {
                    Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                            .show();
                }
                pd.dismiss();
            }

            @Override
            public void failed(String msg) {
                Toast.makeText(mContext,
                        msg,
                        Toast.LENGTH_SHORT).show();
                pd.dismiss();
            }
        },ServiceResult.class);

    }

    /**
     * 更新手机号
     *
     * @param
     */
    private void updateMobile(final String mobile) {

        NetHelper.modifyUserMobile( self, Config.getUserName(), mobile, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                if (rspData.getRetcode() == 0) {
                    int code = 1;
                    String message = null;
                    message = rspData.getMessage();
                    code = rspData.getRetcode();
                    Log.i(TAG,
                            "<updateMobile>--<onResponse>--服务器返回的JSon数据：  message = "
                                    + message);
                    Log.i(TAG,
                            "<updateMobile>--<onResponse>--服务器返回的JSon数据：  code = "
                                    + code);
                    if (code == 0) {
                        Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                                .show();
                        mTvMobile.setText(mobile);
                        HXPreferenceUtils.getInstance()
                                .setCurrentUserMobile(mobile);
                    } else {
                        Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                                .show();
                    }
                    pd.dismiss();
                    hasSendJson = false;
                } else {
                    Toast.makeText(self, rspData.getMessage(), Toast.LENGTH_SHORT).show();
                    pd.dismiss();
                    hasSendJson = false;
                }
            }

            @Override
            public void failed(String msg) {
                Toast.makeText(self, msg, Toast.LENGTH_SHORT).show();
                pd.dismiss();
                hasSendJson = false;
            }
        }, ServiceResult.class);
    }

    public JSONObject getJSON(String sb) throws JSONException {
        return new JSONObject(sb);
    }

    /**
     * dialog的关闭
     *
     * @param dialog
     * @param isClose
     */
    void closeDialog(DialogInterface dialog, boolean isClose) {
        try {
            Field field = dialog.getClass().getSuperclass()
                    .getDeclaredField("mShowing");
            field.setAccessible(true);
            field.set(dialog, isClose);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
